package com.ruge.tool.autosign.job;

import cn.hutool.core.text.StrFormatter;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruge.tool.autosign.api.JinShanApi;
import com.ruge.tool.autosign.api.JueJinApi;
import com.ruge.tool.date.DateTool;
import com.ruge.tool.json.JsonTool;
import com.ruge.tool.sendMsg.DingDingTool;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * JueJinJob
 *
 * @author admin
 * @version 2024/08/05 13:39
 **/
public class JueJinJob {
    /**
     * 掘金等级成长助手
     *
     * @throws Exception
     */
    public static void juejinCheckInAndDraw(String juejin_cookie) throws Exception {
        String result;
        HashMap<String, Object> resultHashMap = new HashMap<>();
        JSONObject todayStatusJSONObject = JueJinApi.getStateOfCheckIn(juejin_cookie);
        JSONObject countOfCheckInJSONObject = JueJinApi.getDayCountOfCheckIn(juejin_cookie);
        if (!"0".equals(todayStatusJSONObject.get("err_no").toString())) {
            resultHashMap.put("cookie", "Cookie失效！请更新有效Cookie");
        } else {
            if ("true".equals(todayStatusJSONObject.get("data").toString())) {
                resultHashMap.put("checkIn", "今日已签到！");
            } else {
                JSONObject checkInHashJSONObject = JueJinApi.checkIn(juejin_cookie);
                if (null == checkInHashJSONObject) {
                    resultHashMap.put("checkIn", "签到接口返回空！");
                } else if ("0".equals(checkInHashJSONObject.get("err_no").toString())) {
                    resultHashMap.put("checkIn", "今日签到成功！获得" + checkInHashJSONObject.getJSONObject("data").get("incr_point").toString() + "矿石！");
                } else {
                    resultHashMap.put("checkIn", "今日签到失败！");
                }
            }
            JSONObject lotteryConfigGetJSONObject = JueJinApi.getCountOfFreeDraw(juejin_cookie);
            if ("0".equals(lotteryConfigGetJSONObject.getJSONObject("data").get("free_count").toString())) {
                resultHashMap.put("draw", "今日已免费抽奖！");
            } else {
                JSONObject drawHashJSONObject = JueJinApi.draw(juejin_cookie);
                if (null == drawHashJSONObject) {
                    resultHashMap.put("draw", "抽奖免费接口返回空！");
                } else if ("0".equals(drawHashJSONObject.get("err_no").toString())) {
                    resultHashMap.put("draw", "免费抽奖获得：" + drawHashJSONObject.getJSONObject("data").get("lottery_name").toString());
                } else {
                    resultHashMap.put("draw", "抽奖免费失败！");
                }
            }
        }
        JSONObject curPointJSONObject = JueJinApi.getCountOfOre(juejin_cookie);

        resultHashMap.put("curPointHashMap", "您的矿石总资产为：" + curPointJSONObject.get("data").toString() + "矿石");
        resultHashMap.put("countOfCheckInHashMap", "您已连续签到" + countOfCheckInJSONObject.getJSONObject("data").get("cont_count").toString() + "天！");
        result = resultHashMap.get("curPointHashMap").toString() + "\n" +
                resultHashMap.get("countOfCheckInHashMap").toString() + "\n" +
                resultHashMap.get("checkIn").toString() + "\n" +
                resultHashMap.get("draw").toString();
        // 通知内容记录到日志
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        DingDingTool.sendMsg("掘金等级成长助手\n通知时间：" + sdf.format(date) + "\n通知内容：" + result);
    }

    // 沸点相关任务
    public static void jueJinGrowth(String juejin_cookie) throws Exception {
        // 调用金山每日一句接口
        JSONObject dailySentenceJsonObject = JinShanApi.dailySentence();
        // 发布第一条沸点
        JueJinApi.publishBoilingPoint(juejin_cookie, JSONObject.parseObject("{\"content\":\"" + dailySentenceJsonObject.get("content").toString().replace(String.valueOf('\"'), "'") + "\",\"sync_to_org\":false}"));
        // 查询前五条最新沸点
        JSONObject boilingPointList = JueJinApi.getBoilingPointList(JSONObject.parseObject("{\"id_type\":4,\"sort_type\":300,\"cursor\":\"0\",\"limit\":5}"));
        for (int i = 0; i < boilingPointList.getJSONArray("data").size(); i++) {
            // 评价前五条最新沸点
            JSONObject boilingPoint = (JSONObject) boilingPointList.getJSONArray("data").get(i);
            JueJinApi.commentBoilingPoint(juejin_cookie, JSONObject.parseObject("{\"client_type\":2608,\"item_id\":\"" + boilingPoint.get("msg_id").toString() + "\",\"item_type\":4,\"comment_content\":\"[发呆][发呆][发呆]好好好，你这么整是吧！\",\"comment_pics\":[]}"));
            Thread.sleep(200);
            // 点赞前五条最新沸点
            JueJinApi.upvoteBoilingPoint(juejin_cookie, JSONObject.parseObject("{\"item_id\":\"" + boilingPoint.get("msg_id").toString() + "\",\"item_type\":4,\"client_type\":2608}"));
        }

        // 文章相关任务
        JSONObject articleListJSONObject = JueJinApi.getArticleList(juejin_cookie);
        JSONArray articleListDataJsonArray = articleListJSONObject.getJSONArray("data");
        // 五篇文章 点赞 + 收藏 + 评论
        for (int i = 0; i < 5; i++) {
            String content_id = articleListDataJsonArray.getJSONObject(i).getJSONObject("content").get("content_id").toString();
            JueJinApi.upvoteArticle(juejin_cookie, JSONObject.parseObject("{\"item_id\":\"" + content_id + "\",\"item_type\":2,\"client_type\":2608}"));
            Thread.sleep(200);
            JueJinApi.addArticle(juejin_cookie, JSONObject.parseObject("{\"article_id\":\"" + content_id + "\",\"select_collection_ids\":[\"7398134415014166562\"],\"unselect_collection_ids\":[\"7398134415014150178\"],\"is_collect_fast\":false}"));
            Thread.sleep(200);
            JueJinApi.articleComment(juejin_cookie, JSONObject.parseObject("{\"client_type\":2608,\"item_id\":\"" + content_id + "\",\"item_type\":2,\"comment_content\":\"大佬666哇[赞][赞][赞]\",\"comment_pics\":[]}"));
            Thread.sleep(200);
        }

        // 关注掘友任务
        JSONObject rankJSONObject = JueJinApi.rank(JSONObject.parseObject("{\"item_rank_type\":1,\"item_sub_rank_type\":\"6809637769959178254\"}"));
        JSONArray rankJsonArray = rankJSONObject.getJSONObject("data").getJSONArray("user_rank_list");
        for (int i = 0; i < 2; i++) {
            JueJinApi.subscribe(juejin_cookie, JSONObject.parseObject("{\"id\":\"" + rankJsonArray.getJSONObject(i).getJSONObject("user_info").get("user_id").toString() + "\",\"type\":1}"));
            Thread.sleep(6000);
            JueJinApi.unSubscribe(juejin_cookie, JSONObject.parseObject("{\"id\":\"" + rankJsonArray.getJSONObject(i).getJSONObject("user_info").get("user_id").toString() + "\",\"type\":1}"));
        }
        // 查询今天累计获得掘金分
        JSONObject taskListJsonObject = JueJinApi.taskList(juejin_cookie, JSONObject.parseObject("{\"growth_type\":1}"));
        // 查询掘友分并拼接消息
        StringJoiner stringJoiner = new StringJoiner("\n\n");
        StringJoiner unstringJoiner = new StringJoiner("\n\n");
        // 获取当前等级信息
        JSONObject progressJSONObject = JueJinApi.progress(juejin_cookie, JSONObject.parseObject("{\"growth_type\":1}"));
        // 获取当前等级最大掘友分！
        JSONArray jsonArray = progressJSONObject.getJSONObject("data").getJSONArray("level_spec");
        List<JSONObject> levelSpecList = jsonArray.stream().map(object -> (JSONObject) object).collect(Collectors.toList());
        levelSpecList.stream().forEach(levelSpec -> {
            if (progressJSONObject.getJSONObject("data").get("current_level").toString().equals(levelSpec.get("level").toString())) {
                stringJoiner.add("距离升级您还差" + (Double.parseDouble(levelSpec.get("max_score").toString()) - Double.parseDouble(progressJSONObject.getJSONObject("data").get("current_score").toString())) + "掘友分！");
            }
        });
        stringJoiner.add("您的掘友等级为：" + progressJSONObject.getJSONObject("data").get("current_level").toString() + "级掘友");
        stringJoiner.add("您的总掘友分为：" + progressJSONObject.getJSONObject("data").get("current_score").toString() + "分");
        stringJoiner.add("今日累计获得" + taskListJsonObject.getJSONObject("data").get("today_jscore").toString() + "掘友分！");
        stringJoiner.add("掘金后台API接口查询明细：");
        JsonTool.getObjToMap(taskListJsonObject.getJSONObject("data").getJSONObject("growth_tasks")).forEach((k, v) -> {
            List<Map<String, Object>> objToMaps = JsonTool.getObjToMaps(v);
            if (!objToMaps.isEmpty()) {
                objToMaps.forEach((i) -> {
                    Object taskType = i.get("task_type");
                    Object title = i.get("title");
                    String btnName = (String) i.get("btn_name");
                    Object score = i.get("score");
                    Object done = i.get("done");
                    Object limit = i.get("limit");
                    String msg = StrFormatter.format("任务类型:{} 任务名称:{} 任务分:{} 已完成次数:{} 总次数:{} {}", taskType, title, score, done, limit, btnName);
                    if (done.equals(limit)) {
                        stringJoiner.add(msg);
                    } else {
                        unstringJoiner.add(msg);
                    }
                });
            }
        });
        stringJoiner.merge(unstringJoiner);
        DingDingTool.sendMsg("掘金等级成长助手\n通知时间：" + DateTool.getLocalDateTime() + "\n通知内容：" + stringJoiner);
    }

    public static void exec(String juejin_cookie) {
        try {
            JueJinJob.juejinCheckInAndDraw(juejin_cookie);
            JueJinJob.jueJinGrowth(juejin_cookie);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
